package net.lahuobao.mall.service.impl.admin;

import net.lahuobao.mall.dao.admin.MallEcardRebateMapper;
import net.lahuobao.mall.entity.admin.MallEcardRebateEntity;
import net.lahuobao.mall.entity.admin.MallEcardRebateOrderEntity;
import net.lahuobao.mall.entity.admin.MallOrderEntity;
import net.lahuobao.mall.entity.admin.MallOrderdetailEntity;
import net.lahuobao.mall.entity.admin.querymodel.MallEcardRebateModel;
import net.lahuobao.mall.service.admin.MallEcardRebateOrderServiceI;
import net.lahuobao.mall.service.admin.MallEcardRebateServiceI;
import net.lahuobao.mall.service.admin.MallOrderdetailServiceI;
import net.lahuobao.mall.service.admin.MallorderServiceI;
import net.lahuobao.util.httpClientUtil;
import net.sf.json.JSONObject;
import org.apache.http.message.BasicNameValuePair;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("mallEcardRebateService")
@Transactional
public class MallEcardRebateServiceImpl extends CommonServiceImpl implements MallEcardRebateServiceI {

    @Autowired
    private MallorderServiceI orderService;

    @Autowired
    private MallOrderdetailServiceI orderdetailService;

    @Autowired
    private MallEcardRebateOrderServiceI ecardRebateOrderService;

    @Autowired
    private MallEcardRebateMapper mapper;

    @Override
    public Map<MallOrderEntity, List<MallOrderdetailEntity>> selectOrderDetailByOrderIds(Integer[] ids) {
        //返回
        Map<MallOrderEntity, List<MallOrderdetailEntity>> result = new HashMap<MallOrderEntity, List<MallOrderdetailEntity>>();
        //遍历
        for (Integer orderId : ids) {
            //获取订单
            MallOrderEntity orderEntity = orderService.getEntity(MallOrderEntity.class, orderId);
            //获取详情
            List<MallOrderdetailEntity> orderdetailEntities = orderdetailService.selectByOrderIdAndType(orderId, orderEntity.getOrdertype());
            result.put(orderEntity, orderdetailEntities);
        }
        return result;
    }

    /**
     * @param rebateEntity
     * @param orderIds
     */
    @Override
    public AjaxJson rebate(MallEcardRebateEntity rebateEntity, String orderIds) throws UnsupportedEncodingException {
        AjaxJson result = new AjaxJson();
        //验证信息
        //判断返点类型 0:点数,1:直返
        if (rebateEntity.getRebatetype() == 0) {
            String reg = "^([0-5]|6|6.0|6.00)(\\.\\d{1,2})?$";
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(rebateEntity.getRebatenum().toString());
            if (!m.matches()) {
                result.setSuccess(false);
                result.setMsg("返点数需大于0小于等于6！");
                return result;
            } else {
                BigDecimal rebatenum = new BigDecimal(rebateEntity.getRebatenum().toString());
                if (rebatenum.compareTo(new BigDecimal(0)) == 0) {
                    result.setSuccess(false);
                    result.setMsg("返点数需大于0小于等于6！");
                    return result;
                }
            }
        }

        //直返
        if (rebateEntity.getRebatetype() == 1) {
            String reg = "^([1-9]\\d*|0)(\\.\\d{1,2})?$";
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(rebateEntity.getRebatemoney().toString());
            if (!m.matches()) {
                result.setSuccess(false);
                result.setMsg("请输入正确的返点金额！");
                return result;
            } else {
                if (rebateEntity.getRebatemoney().compareTo(new BigDecimal(0)) == 0) {
                    result.setSuccess(false);
                    result.setMsg("请输入正确的返点金额！");
                    return result;
                }
            }
        }

        String[] orderIdsArrays = orderIds.split(",");
        List<Integer> orderIdLists = new ArrayList<Integer>();
        Integer[] orderIdArraysInteger = new Integer[orderIdsArrays.length];
        //lists
        for (int i = 0; i < orderIdsArrays.length; i++) {
            orderIdLists.add(Integer.parseInt(orderIdsArrays[i]));
        }
        //array
        for (int i = 0; i < orderIdsArrays.length; i++) {
            orderIdArraysInteger[i] = Integer.parseInt(orderIdsArrays[i]);
        }
        //返点实例
        MallEcardRebateEntity resultEcard = null;
        //判断是否已经返点
        List<MallEcardRebateOrderEntity> mallEcardRebateOrders = ecardRebateOrderService.selectByorderIds(orderIdArraysInteger);
        if(rebateEntity.getId() != null){
            resultEcard = super.get(MallEcardRebateEntity.class, rebateEntity.getId());
        }
        //中间表有数据，并且复核状态为通过
        if (mallEcardRebateOrders.size() > 0 && resultEcard.getRebateauditstate() == 1) {
            result.setSuccess(false);
            result.setMsg("系统异常");
            return result;
        }
        //实际支付总金额
        BigDecimal actualPayTotalMoney = new BigDecimal(0);
        //订单总金额
        BigDecimal orderTotalMoney = new BigDecimal(0);
        //返点金额
        BigDecimal rebateMoney = new BigDecimal(0);
        //用户id
        String userId = null;
        //获取订单金额
        List<MallOrderEntity> results = orderService.selectByIds(orderIdArraysInteger);

        if (results.size() > 0) {
            userId = results.get(0).getUserid().toString();
        }

        //遍历list 判断用户和计算金额
        for (MallOrderEntity mallOrderEntity : results) {
            if (!userId.equals(mallOrderEntity.getUserid().toString())) {
                result.setSuccess(false);
                result.setMsg("同一用户才能设置批量E卡返点");
                return result;
            } else {
                userId = mallOrderEntity.getUserid().toString();
                orderTotalMoney = orderTotalMoney.add(mallOrderEntity.getPaymoney());
                actualPayTotalMoney = actualPayTotalMoney.add(mallOrderEntity.getActualPayMoney());
            }
        }

        //判断返点类型 0:点数,1:直返
        //点数
        if (rebateEntity.getRebatetype() == 0) {
            //返点金额 == 订单金额 * （点数/100）
            rebateMoney = orderTotalMoney.multiply(rebateEntity.getRebatenum().divide(new BigDecimal(100)));
        }

        //判断返点类型 0:点数,1:直返
        //直返
        if (rebateEntity.getRebatetype() == 1) {
            rebateMoney = rebateEntity.getRebatemoney();
            rebateEntity.setRebatenum(new BigDecimal(0));
        }

        //比较返点金额
        if (rebateMoney.compareTo(actualPayTotalMoney) == 1) {
            result.setSuccess(false);
            result.setMsg("返点金额不能大于实际支付金额！");
            return result;
        } else {
            rebateEntity.setRebatemoney(rebateMoney);
        }
        //判断是否重新发起返点请求
        if(rebateEntity.getId() != null){
            if(resultEcard.getRebateauditstate() == 2){//未通过
                try {
                    //更新原有数据
                    //复核状态为未复核
                    resultEcard.setRebateauditstate(0);
                    //清除相关复核数据
                    resultEcard.setRebateauditoperator(null);
                    resultEcard.setRebatereviewtime(null);
                    resultEcard.setRebaterejectreason(null);
                    MyBeanUtils.copyBeanNotNull2Bean(rebateEntity, resultEcard);
                    super.saveOrUpdate(resultEcard);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                result.setSuccess(false);
                result.setMsg("系统异常,请稍候再试");
                return result;
            }
        }else{//第一次
            //写入主表 --mall_ecard_rebate
            //状态为返点
            rebateEntity.setState(0);
            //返点复核状态为待审核
            rebateEntity.setRebateauditstate(0);
            rebateEntity.setRebatetime(new Date());
            Integer revateId = (Integer) super.save(rebateEntity);
            //写入关系表 -- mall_ecard_rebate_order
            List<MallEcardRebateOrderEntity> batchInsert = new ArrayList<MallEcardRebateOrderEntity>();
            for (MallOrderEntity mallOrderEntity : results) {
                MallEcardRebateOrderEntity insertParam = new MallEcardRebateOrderEntity();
                insertParam.setOrderid(mallOrderEntity.getId());
                insertParam.setEcardrebateid(revateId);
                batchInsert.add(insertParam);
            }
            super.batchSave(batchInsert);
        }
        return result;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Map<MallOrderEntity, List<MallOrderdetailEntity>> selectOrderDetailById(Integer id) {
        //获取关系表订单id
        CriteriaQuery cq = new CriteriaQuery(MallEcardRebateOrderEntity.class);
        cq.eq("ecardrebateid", id);
        cq.add();
        List<MallEcardRebateOrderEntity> ecardRebateOrderLists = super.getListByCriteriaQuery(cq, false);
        Integer[] orderIds = new Integer[ecardRebateOrderLists.size()];
        for (int i = 0; i < ecardRebateOrderLists.size(); i++) {
            orderIds[i] = ecardRebateOrderLists.get(i).getOrderid();
        }
        return this.selectOrderDetailByOrderIds(orderIds);
    }

    /**
     * e卡返点退回
     *
     * @param updateRebateEntity
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public AjaxJson rebateReturn(MallEcardRebateEntity updateRebateEntity) throws Exception {
        AjaxJson resultjson = new AjaxJson();
        //验证退回金额 0 ,<0
        if (updateRebateEntity.getReturnmoney().compareTo(new BigDecimal(0)) == 0 ||
                updateRebateEntity.getReturnmoney().compareTo(new BigDecimal(0)) == -1) {
            resultjson.setSuccess(false);
            resultjson.setMsg("退回金额异常");
            return resultjson;
        }
        MallEcardRebateEntity resultRebate = super.getEntity(MallEcardRebateEntity.class, updateRebateEntity.getId());
        //验证退回金额 <= 返点金额
        if (updateRebateEntity.getReturnmoney().compareTo(resultRebate.getRebatemoney()) == 1) {
            resultjson.setSuccess(false);
            resultjson.setMsg("退回金额不能大于返点金额");
            return resultjson;
        }

        //查询关系表中的订单 根据主表id
        CriteriaQuery cq = new CriteriaQuery(MallEcardRebateOrderEntity.class);
        cq.eq("ecardrebateid", resultRebate.getId());
        cq.add();
        List<MallEcardRebateOrderEntity> ecardRebateOrderLists = super.getListByCriteriaQuery(cq, false);
        if (ecardRebateOrderLists.size() == 0) {
            resultjson.setSuccess(false);
            resultjson.setMsg("系统异常，请稍后再试！");
            return resultjson;
        }
        //更新表数据
        Integer returnType = updateRebateEntity.getReturnmoney().compareTo(resultRebate.getRebatemoney()) == 0 ? 2 : 1;
        //状态为退回
        updateRebateEntity.setState(returnType);
        //退回金额
        updateRebateEntity.setRebatemoney(resultRebate.getRebatemoney().subtract(updateRebateEntity.getReturnmoney()));
        //退回时间
        updateRebateEntity.setReturntime(new Date());
        //退回复核状态为待复核
        updateRebateEntity.setReturnauditstate(0);
        if(null != resultRebate.getReturnauditstate() && resultRebate.getReturnauditstate() == 2){
            //清除以前复核信息
            updateRebateEntity.setReturnrejectreason(null);
            updateRebateEntity.setReturnauditoperator(null);
            updateRebateEntity.setReturnreviewtime(null);
        }
        //更新
        MyBeanUtils.copyBeanNotNull2Bean(updateRebateEntity, resultRebate);
        super.saveOrUpdate(resultRebate);
        return resultjson;
    }

    /**
     * e卡返点，退回审核
     *
     * @param mallEcardRebate
     * @return
     */
    @Override
    public AjaxJson audit(MallEcardRebateEntity mallEcardRebate) {
        AjaxJson resultJson = new AjaxJson();
        //判断审核类型
        if (mallEcardRebate.getState() == 0) {//返点
            resultJson = rebateAudit(mallEcardRebate);
        } else {//退回
            resultJson = returnAudit(mallEcardRebate);
        }
        return resultJson;
    }

    /**
     * e卡返点复核
     *
     * @param mallEcardRebate
     * @return
     */
    private AjaxJson rebateAudit(MallEcardRebateEntity mallEcardRebate) {
        AjaxJson resultJson = new AjaxJson();
        MallEcardRebateEntity resultRebate = super.getEntity(MallEcardRebateEntity.class, mallEcardRebate.getId());
        if (resultRebate.getRebateauditstate() != 0) {
            resultJson.setSuccess(false);
            resultJson.setMsg("系统出错，请稍后再试！");
            return resultJson;
        }
        //判断复核结果
        //更新对象
        MallEcardRebateEntity updateRebateEntity = new MallEcardRebateEntity();
        HttpSession session = ContextHolderUtils.getSession();
        TSUser user = (TSUser) session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
        try {
            //通过
            if (mallEcardRebate.getRebateauditstate() == 1) {
                //获取返点金额
                BigDecimal rebateMoney = resultRebate.getRebatemoney();
                //获取返点人
                List<MallEcardRebateOrderEntity> ecardRebateOrderEntities = ecardRebateOrderService.selectByEcardRebateId(mallEcardRebate.getId());
                MallOrderEntity mallOrderEntity = orderService.getEntity(MallOrderEntity.class, ecardRebateOrderEntities.get(0).getOrderid());
                //调用接口
                ResourceBundle bundle = PropertyResourceBundle.getBundle("shopping");
                String url = bundle.getString("lhbmall") + bundle.getString("ecardrebate");

                List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
                nvps.add(new BasicNameValuePair("userId", String.valueOf(mallOrderEntity.getUser().getId())));
                nvps.add(new BasicNameValuePair("money", String.valueOf(rebateMoney.setScale(2, BigDecimal.ROUND_HALF_UP))));
                nvps.add(new BasicNameValuePair("orderId", String.valueOf(mallOrderEntity.getId())));
                JSONObject json = httpClientUtil.httpPost(url, nvps, false);
                //处理接口返回信息
                if (json != null && (Boolean) json.get("handleState")) {//成功
                    //更新数据
                    //复核状态通过
                    updateRebateEntity.setRebateauditstate(1);
                    //复核人
                    updateRebateEntity.setRebateauditoperator(user.getId());
                    //复核时间
                    updateRebateEntity.setRebatereviewtime(new Date());
                    MyBeanUtils.copyBeanNotNull2Bean(updateRebateEntity, resultRebate);
                    super.saveOrUpdate(resultRebate);
                } else {//失败
                    resultJson.setSuccess(false);
                    resultJson.setMsg(null == json ? "系统异常" : json.get("message").toString());
                    return  resultJson;
                }
            }
            //不通过
            if (mallEcardRebate.getRebateauditstate() == 2) {
                //更新数据
                //复核状态不通过
                updateRebateEntity.setRebateauditstate(2);
                //复核人
                updateRebateEntity.setRebateauditoperator(user.getId());
                //复核时间
                updateRebateEntity.setRebatereviewtime(new Date());
                //不通过原因
                updateRebateEntity.setRebaterejectreason(mallEcardRebate.getRebaterejectreason());
                MyBeanUtils.copyBeanNotNull2Bean(updateRebateEntity, resultRebate);
                super.saveOrUpdate(resultRebate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.setSuccess(false);
            resultJson.setMsg("系统出错，请稍后再试！");
        }
        return resultJson;
    }

    /**
     * e卡退回复核
     *
     * @param mallEcardRebate
     * @return
     */
    private AjaxJson returnAudit(MallEcardRebateEntity mallEcardRebate) {
        AjaxJson resultJson = new AjaxJson();
        MallEcardRebateEntity resultRebate = super.getEntity(MallEcardRebateEntity.class, mallEcardRebate.getId());
        if (resultRebate.getReturnauditstate() != 0) {
            resultJson.setSuccess(false);
            resultJson.setMsg("系统出错，请稍后再试！");
            return resultJson;
        }
        //判断复核结果
        //更新对象
        MallEcardRebateEntity updateRebateEntity = new MallEcardRebateEntity();
        HttpSession session = ContextHolderUtils.getSession();
        TSUser user = (TSUser) session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
        try {
            //通过
            if (mallEcardRebate.getReturnauditstate() == 1) {
                //获取退回金额
                BigDecimal returnMoney = resultRebate.getReturnmoney();
                //获取返点人
                List<MallEcardRebateOrderEntity> ecardRebateOrderEntities = ecardRebateOrderService.selectByEcardRebateId(mallEcardRebate.getId());
                MallOrderEntity mallOrderEntity = orderService.getEntity(MallOrderEntity.class, ecardRebateOrderEntities.get(0).getOrderid());
                //调用接口
                ResourceBundle bundle = PropertyResourceBundle.getBundle("shopping");
                String url = bundle.getString("lhbmall") + bundle.getString("ecardreturn");

                List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
                nvps.add(new BasicNameValuePair("userId", String.valueOf(mallOrderEntity.getUser().getId())));
                nvps.add(new BasicNameValuePair("money", String.valueOf(returnMoney.setScale(2, BigDecimal.ROUND_HALF_UP))));
                nvps.add(new BasicNameValuePair("orderId", String.valueOf(mallOrderEntity.getId())));
                JSONObject json = httpClientUtil.httpPost(url, nvps, false);
                //处理接口返回信息
                if (json != null && (Boolean) json.get("handleState")) {//成功
                    //更新数据
                    //复核状态通过
                    updateRebateEntity.setReturnauditstate(1);
                    //复核人
                    updateRebateEntity.setReturnauditoperator(user.getId());
                    //复核时间
                    updateRebateEntity.setReturnreviewtime(new Date());
                    MyBeanUtils.copyBeanNotNull2Bean(updateRebateEntity, resultRebate);
                    super.saveOrUpdate(resultRebate);
                } else {//失败
                    resultJson.setSuccess(false);
                    resultJson.setMsg(null == json ? "系统异常" : json.get("message").toString());
                    return  resultJson;
                }
            }
            //不通过
            if (mallEcardRebate.getReturnauditstate() == 2) {
                //更新数据
                //复核状态不通过
                updateRebateEntity.setReturnauditstate(2);
                //复核人
                updateRebateEntity.setReturnauditoperator(user.getId());
                //复核时间
                updateRebateEntity.setReturnreviewtime(new Date());
                //不通过原因
                updateRebateEntity.setReturnrejectreason(mallEcardRebate.getReturnrejectreason());
                //计算返点金额
                updateRebateEntity.setRebatemoney(resultRebate.getRebatemoney().add(resultRebate.getReturnmoney()));
                updateRebateEntity.setReturnmoney(new BigDecimal(0));
                MyBeanUtils.copyBeanNotNull2Bean(updateRebateEntity, resultRebate);
                super.saveOrUpdate(resultRebate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.setSuccess(false);
            resultJson.setMsg("系统出错，请稍后再试！");
        }
        return resultJson;
    }


    /**
     * 根据条件查询
     * @param query
     * @return
     */
    @Override
    public List<MallEcardRebateModel> selectRebateListByquery(MallEcardRebateModel query) {
        return mapper.selectRebateListByquery(query, getPageBounds());
    }
}